#include "Queue.h"

void QueueInit(Queue* pqueue) {
	assert(pqueue);  
	pqueue->_head = pqueue->_tail = NULL;
}

void QueueDestory(Queue* pqueue) {
	assert(pqueue);   QueueNode* temp = NULL;
	QueueNode* cur = pqueue->_head;
	while (cur) {
		temp = cur;   cur = cur->_next; 
		free(temp);
	}   pqueue->_head = pqueue->_tail = NULL;
}

void QueuePrint(Queue* pqueue) {
	assert(pqueue);  QueueNode* cur = pqueue->_head;
	printf("(队头) ");
	while (cur) {
		printf("%d -> ", cur->_data);
		cur = cur->_next;
	}   printf("NULL (队尾)\n");
}

void QueuePush(Queue* pqueue, QueueDataType value) {
	assert(pqueue);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	newnode->_data = value;   newnode->_next = NULL;
	if (!pqueue->_head) {
		pqueue->_head = pqueue->_tail = newnode;
	}
	else {
		pqueue->_tail->_next = newnode;
		pqueue->_tail = newnode;
	}
}

void QueuePop(Queue* pqueue) {
	assert(pqueue);   if (!pqueue->_head) { return; }
	QueueNode* temp = pqueue->_head;
	pqueue->_head = temp->_next;   free(temp);
	// 若无节点了，则_tail仍指向原队尾结点，为野指针
	if (pqueue->_head == NULL) { pqueue->_tail == NULL; }
}

QueueDataType QueueFront(Queue* pqueue) {
	assert(pqueue);   assert(pqueue->_head);
	return pqueue->_head->_data;
}

QueueDataType Queueback(Queue* pqueue) {
	assert(pqueue);   assert(pqueue->_tail);
	return pqueue->_tail->_data;
}

bool QueueEmpty(Queue* pqueue) {
	assert(pqueue);
	return (pqueue->_head == NULL) ? 1 : 0;
}

int QueueSize(Queue* pqueue) {
	assert(pqueue);   int size = 0;
	QueueNode* cur = pqueue->_head;
	while (cur) { ++size;  cur = cur->_next; }
	return size;
}